const mysql = require("mysql")

const pool = mysql.createPool({
    host: "localhost",
    user: "root",
    password: "",
    database: "zhixin",
    timezone: "08:00"
})

function doSQL(sql, params = []) {
    return new Promise((relove, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                reject(err)
            } else {
                connection.query(sql, params, (err, data, fields) => {
                    connection.release() // 释放连接
                    relove({ err, data, fields })
                })
            }
        })
    })
}

function handleResults(results, total) {
    // console.log(results)
    return JSON.stringify({
        success: true,
        errorCode: 0,
        code: 20000,
        msg: '数据请求成功',
        data: results,
        total,
    })
}

function handleNoResults() {
    return JSON.stringify({
        success: true,
        errorCode: 4001,
        msg: '接口没有数据',
    })
}

function handleError() {
    return JSON.stringify({
        success: false,
        errorCode: 410,
        msg: '接口调用失败',
    })
}

function handleListResults(results, total = 0) {
    return JSON.stringify({
        success: true,
        errorCode: 0,
        code: 20000,
        msg: '数据请求成功',
        data: results,
        total
    })
}

module.exports = {
    doSQL: doSQL,
    handleResults: handleResults,
    handleNoResults: handleNoResults,
    handleError: handleError,
    handleListResults: handleListResults,
}
